package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一步交互由三部分构成
 * 1：解析请求
 * 2：处理请求
 * 3：响应客户端
 */

public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //.1解析请求
            //1.1读取请求行

            String line = readLine();
            System.out.println(line);
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议版本
            String[] gg = line.split("\\s");
            method = gg[0];
            uri = gg[1];//这里后期会出现数组下表越界异常，这是由于空请求造成的，后期解决
            protocol = gg[2];
            System.out.println("method:" + method);
            System.out.println("uri:" + uri);
            System.out.println("protocol:" + protocol);
            //1.2解析消息头
            Map<String,String> headers=new HashMap<>();
            while (true) {
                line = readLine();
                if (line.isEmpty()) {
                    break;
                }
                String[] sub=line.split(":\\s");
                headers.put(sub[0],sub[1]);
                System.out.println("消息头" + line);
            }
            System.out.println("headers"+headers);
            //:2处理请求

            //:3发送响应


            /*
                上述内容写好后，打开浏览器输入网址:http://localhost:8088/index.html
                测试读取浏览器发送过来的请求内容并在控制台上确认内容
             */
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //一次http交互后要与客户端断开链接（HTTP协议要求）
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char pre = 'a', cure = 'a';//pre表示上次读取到的字符，cure表示本次读取到的字符
        while ((d = in.read()) != -1) {
            cure = (char) d;
            if (cure == 10 && pre == 13) {
                break;
            }
            builder.append(cure);
            pre = cure;
        }
        String line = builder.toString().trim();
        return line;
    }
}
